package com.cspg.design.ui.pointDevice;

import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.cspg.design.CSPGApplication;
import com.cspg.design.R;
import com.cspg.design.bean.UserInfo;
import com.cspg.design.bean.deviceBean.PointDeviceBean;
import com.cspg.design.bean.deviceBean.PolylineDeviceBean;
import com.cspg.design.bean.modelLibrary.WireLibrary;
import com.cspg.design.bean.projectBean.ProjectBean;
import com.cspg.design.bean.shemeBean.MyHighVoltageSchemeBean;
import com.cspg.design.bean.shemeBean.MyLowVoltageSchemeBean;
import com.cspg.design.dao.gen.DaoSession;
import com.cspg.design.dao.gen.MyHighVoltageSchemeBeanDao;
import com.cspg.design.dao.gen.MyLowVoltageSchemeBeanDao;
import com.cspg.design.dao.gen.PointDeviceBeanDao;
import com.cspg.design.dao.gen.PolylineDeviceBeanDao;
import com.cspg.design.dao.gen.ProjectBeanDao;
import com.cspg.design.dao.gen.WireLibraryDao;
import com.cspg.design.utils.ActionBarUtil;
import com.cspg.design.utils.StatusBarUtil;
import com.cspg.design.widget.AlertListDialog;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

public class PolylineDeviceActivity extends AppCompatActivity {
    private EditText et_end_point_name; //本桩位
    private EditText et_pre_point_name;//前桩位
    private EditText et_status;//状态
    private EditText et_distance;//档距
    private EditText et_wire_model;//导向型号
    private EditText et_circuits_number;//回路数
    private EditText et_margin;//裕度
    private EditText et_cross_section;//截面积
    private EditText et_wire_material_quality;//导线材质

    private DaoSession daoSession;
    private PolylineDeviceBean polyline;
    private String[] wireModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_polyline_device);
        StatusBarUtil.setStatusBarColor(this, R.color.colorPrimary);
        ActionBarUtil.setActionBar(this, R.string.point_device_title);
        et_status = findViewById(R.id.et_status);
        et_distance = findViewById(R.id.et_distance);
        et_end_point_name = findViewById(R.id.et_end_point_name);
        et_pre_point_name = findViewById(R.id.et_pre_point_name);
        et_wire_model = findViewById(R.id.et_wire_model);
        et_circuits_number = findViewById(R.id.et_circuits_number);
        et_margin = findViewById(R.id.et_margin);
        et_cross_section = findViewById(R.id.et_cross_section);
        et_wire_material_quality = findViewById(R.id.et_wire_material_quality);
        et_wire_model.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertListDialog.ListBuilder(PolylineDeviceActivity.this)
                        .setDividerColorRes(R.color.color_divider)
                        .setDividerHeightRes(R.dimen.dp1)
                        .setTitle("请选择设备状态")
                        .setIcon(R.drawable.ic_info)
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .setItems(wireModel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                et_wire_model.setText(wireModel[which]);
                            }
                        }).create().show();

            }
        });
        Button btn_save = findViewById(R.id.btn_polyline_device_save);
        if (UserInfo.getInstance().role.contains("设计"))
        {
            btn_save.setVisibility(View.GONE);
        }
        btn_save.setOnClickListener(v -> {
            polyline.setPolylineModel(et_wire_model.getText().toString());
            polyline.setCircuitsNum(et_circuits_number.getText().toString().trim());
            polyline.setMargin(et_margin.getText().toString().trim());
            updateData(polyline);
        });
        String uuid = getIntent().getStringExtra("uuid");
        daoSession = ((CSPGApplication) getApplication()).getDaoSession();
        initData(uuid);
    }

    private void initData(String uuid) {
        if (uuid != null && !uuid.isEmpty()) {
            daoSession.getPolylineDeviceBeanDao()
                    .queryBuilder()
                    .where(PolylineDeviceBeanDao.Properties.PolylineUuid.eq(uuid))
                    .rx()
                    .unique()
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<PolylineDeviceBean>() {
                        @Override
                        public void call(PolylineDeviceBean polylineDeviceBean) {
                            if (polylineDeviceBean == null) {
                                return;
                            }
                            polyline = polylineDeviceBean;
                            et_wire_model.setText(polylineDeviceBean.getPolylineModel());
                            String startPointUUID = polylineDeviceBean.getStartPointUUID();
                            String endPointUUID = polylineDeviceBean.getEndPointUUID();
                            PointDeviceBean startPointDeviceBean = daoSession.getPointDeviceBeanDao()
                                    .queryBuilder()
                                    .where(PointDeviceBeanDao.Properties.PointUuid.eq(startPointUUID))
                                    .unique();
                            PointDeviceBean endPointDeviceBean = daoSession.getPointDeviceBeanDao()
                                    .queryBuilder()
                                    .where(PointDeviceBeanDao.Properties.PointUuid.eq(endPointUUID))
                                    .unique();
                            if (startPointDeviceBean != null) {
                                et_pre_point_name.setText(startPointDeviceBean.getPointName());
                            }
                            if (endPointDeviceBean != null) {
                                et_end_point_name.setText(endPointDeviceBean.getPointName());
                                int status = endPointDeviceBean.getPointStatue();
                                String label = "";
                                switch (status) {
                                    case 1:
                                        label = "新增";
                                        break;
                                    case 2:
                                        label = "利旧";
                                        break;
                                }
                                et_status.setText(label);
                            }
                            List<WireLibrary> wireLibrarys = daoSession
                                    .getWireLibraryDao()
                                    .queryBuilder()
                                    .where(WireLibraryDao.Properties.WireModel.eq(polylineDeviceBean.getPolylineModel()))
                                    .list();
                            WireLibrary wireLibrary = wireLibrarys.size() > 0 ? wireLibrarys.get(0) : null;
                            if (wireLibrary != null) {
                                et_wire_material_quality.setText(wireLibrary.getWireQuality());
                                et_cross_section.setText(wireLibrary.getWireCrossSection());
                            }
                            Double length = DistanceUtil.getDistance(
                                    new LatLng(startPointDeviceBean.getLatitude(), startPointDeviceBean.getLongitude()),
                                    new LatLng(endPointDeviceBean.getLatitude(), endPointDeviceBean.getLongitude()));
                            length = new BigDecimal(length).setScale(2, RoundingMode.UP).doubleValue();
                            et_distance.setText(String.valueOf(length));
                            ProjectBean projectBean = daoSession.getProjectBeanDao()
                                    .queryBuilder()
                                    .where(ProjectBeanDao.Properties.ProjectId.eq(polyline.getProjectId()))
                                    .unique();
                            String schemeType = projectBean.getSchemaType();
                            String schemeName = projectBean.getSchemeName();
                            if (schemeType.equals("low")) {
                                MyLowVoltageSchemeBean myLowVoltageSchemeBean = daoSession.getMyLowVoltageSchemeBeanDao().queryBuilder()
                                        .where(MyLowVoltageSchemeBeanDao.Properties.SchemeName.eq(schemeName),
                                                MyLowVoltageSchemeBeanDao.Properties.UserName.eq(projectBean.getUserName()))
                                        .unique();
                                String wire380 = myLowVoltageSchemeBean.getWireModel380V();
                                String wire220 = myLowVoltageSchemeBean.getWireModel220V();
                                if (wire220 != null && !wire220.isEmpty() && wire380 != null && !wire380.isEmpty()) {
                                    wireModel = new String[2];
                                    wireModel[0] = wire380;
                                    wireModel[1] = wire220;
                                } else if (wire380 == null || wire380.isEmpty()) {
                                    wireModel = new String[1];
                                    wireModel[0] = wire220;
                                } else if (wire220 == null || wire220.isEmpty()) {
                                    wireModel = new String[1];
                                    wireModel[0] = wire380;
                                }
                            } else if (schemeType.equals("high")) {
                                MyHighVoltageSchemeBean myHighVoltageSchemeBean = daoSession.getMyHighVoltageSchemeBeanDao().queryBuilder()
                                        .where(MyHighVoltageSchemeBeanDao.Properties.SchemeName.eq(schemeName),
                                                MyHighVoltageSchemeBeanDao.Properties.UserName.eq(projectBean.getUserName()))
                                        .unique();
                                String model = myHighVoltageSchemeBean.getWireModel();
                                wireModel = new String[1];
                                wireModel[0] = model;
                            }
                        }
                    });
        }
    }

    private void updateData(PolylineDeviceBean polyline) {
        daoSession.getPolylineDeviceBeanDao().update(polyline);
        Toast.makeText(this, "更新成功。。。。", Toast.LENGTH_LONG).show();
    }


}